package com.dxq.test.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dxq.test.App;
import com.dxq.test.common.AppManager;
import com.dxq.test.common.Constant;
import com.dxq.test.R;
import com.dxq.test.db.Breed;
import com.dxq.test.db.Event;
import com.dxq.test.db.Label;
import com.dxq.test.db.LabelBreed;
import com.dxq.test.db.Pasture;
import com.dxq.test.db.TablesDao;
import com.dxq.test.db.Vaccine;
import com.dxq.test.utils.DialogClickListener;
import com.dxq.test.utils.MyUtil;

import java.util.Date;
import java.util.List;

/**
 * Author: zsh
 * Date: 2023/10/19
 * Describe: 标签添加
 */
public class LabelAddActivity extends AppCompatActivity implements View.OnClickListener {

    public TablesDao tablesDao;

    private String[] types = {"牛", "羊", "禽类"};

    private ImageView ivBack;
    private EditText etSerialNumber, etName, etWeight;
    private Button btnScan, btnSubmit;
    private TextView tvTitle, tvSet, tvBatteryLevel, tvTemperature, tvExerciseSteps, tvType;
    private RadioGroup rgSex, rgBreedingStatus;
    private RadioButton rbg, rbm, rbb1, rbb2, rbb3;
    private Spinner spType;

    private String sex = "";
    private String breedingStatus = "";
    private String QRCodeID = "";
    private int type = -1;

    private Label selectLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //添加Activity到堆栈
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_label_add);
        selectLabel = (Label) getIntent().getSerializableExtra("label");
        tablesDao = new TablesDao(this);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在appManager结束当前activity
        AppManager.getAppManager().finishActivity(this);
    }

    private void initView() {
        ivBack = findViewById(R.id.ivBack);
        tvTitle = findViewById(R.id.tvTitle);
        tvSet = findViewById(R.id.tvSet);

        etSerialNumber = findViewById(R.id.etSerialNumber);
        etName = findViewById(R.id.etName);
        etWeight = findViewById(R.id.etWeight);
        btnScan = findViewById(R.id.btnScan);
        btnSubmit = findViewById(R.id.btnSubmit);
        tvBatteryLevel = findViewById(R.id.tvBatteryLevel);
        tvTemperature = findViewById(R.id.tvTemperature);
        tvExerciseSteps = findViewById(R.id.tvExerciseSteps);
        tvType = findViewById(R.id.tvType);
        rgSex = findViewById(R.id.rgSex);
        rgBreedingStatus = findViewById(R.id.rgBreedingStatus);
        rbg = findViewById(R.id.rbg);
        rbm = findViewById(R.id.rbm);
        rbb1 = findViewById(R.id.rbb1);
        rbb2 = findViewById(R.id.rbb2);
        rbb3 = findViewById(R.id.rbb3);
        spType = findViewById(R.id.spType);

        if (null == selectLabel) {
            tvTitle.setText("牲畜添加");

            rbg.setChecked(true);
            sex = Constant.SEX_MAN;
            //默认值
            rbb1.setChecked(true);
            breedingStatus = Constant.BREEDSTATUS_CUNLAN;
        } else {
            tvTitle.setText("牲畜详情");
            tvSet.setText("删除");
            tvSet.setVisibility(View.VISIBLE);

            //设置值
            etName.setText(selectLabel.getName());
            etWeight.setText(selectLabel.getWeight());
            sex = selectLabel.getSex();
            if (sex.equals(Constant.SEX_MAN))
                rbg.setChecked(true);
            if (sex.equals(Constant.SEX_WOMAN))
                rbm.setChecked(true);
            rbg.setEnabled(false);//禁止更改性别
            rbm.setEnabled(false);//禁止更改性别
            breedingStatus = selectLabel.getBreedingStatus();
            if (breedingStatus.equals(Constant.BREEDSTATUS_CUNLAN))
                rbb1.setChecked(true);
            if (breedingStatus.equals(Constant.BREEDSTATUS_CHULAN))
                rbb2.setChecked(true);
            if (breedingStatus.equals(Constant.BREEDSTATUS_SIWANG))
                rbb3.setChecked(true);
            etSerialNumber.setText(selectLabel.getSerialNumber());
            tvBatteryLevel.setText(selectLabel.getBatteryLevel());
            tvTemperature.setText(selectLabel.getTemperature());
            tvExerciseSteps.setText(selectLabel.getExerciseSteps());
        }

        btnScan.setOnClickListener(this);
        tvSet.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
        ivBack.setOnClickListener(this);

        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbg:
                        sex = Constant.SEX_MAN;
                        break;

                    case R.id.rbm:
                        sex = Constant.SEX_WOMAN;
                        break;
                }
            }
        });

        rgBreedingStatus.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbb1:
                        breedingStatus = Constant.BREEDSTATUS_CUNLAN;
                        break;

                    case R.id.rbb2:
                        breedingStatus = Constant.BREEDSTATUS_CHULAN;
                        break;

                    case R.id.rbb3:
                        breedingStatus = Constant.BREEDSTATUS_SIWANG;
                        break;
                }
            }
        });

        // 声明一个ArrayAdapter用于存放简单数据
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                LabelAddActivity.this, android.R.layout.simple_spinner_dropdown_item, types);
        // 把定义好的Adapter设定到spinner中
        spType.setAdapter(adapter);
        // 为第一个Spinner设定选中事件
        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                //在选中之后触发
                type = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 这个一直没有触发，我也不知道什么时候被触发。
                //在官方的文档上说明，为back的时候触发，但是无效，可能需要特定的场景
            }
        });

        //默认值
        tvType.setText(types[App.select_label_type]);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                LabelAddActivity.this.finish();
                break;

            case R.id.btnScan:
                Toast.makeText(LabelAddActivity.this, "随机生成标签信息", Toast.LENGTH_SHORT).show();
                etSerialNumber.setText("A" + System.currentTimeMillis());
                tvBatteryLevel.setText("85");
                tvTemperature.setText("25");
                tvExerciseSteps.setText("1200");
                break;

            case R.id.btnSubmit:
                if (null != selectLabel)
                    updateLabel();
                else
                    addLabel();
                break;

            case R.id.tvSet://删除牲畜
                MyUtil.normalDialog(LabelAddActivity.this, "操作提示", "是否删除牲畜信息？",
                        "取消", "确定", new DialogClickListener() {

                            @Override
                            public void onNegativeClick() {

                            }

                            @Override
                            public void onPositiveClick() {
                                deleteLabel();
                            }
                        });
                break;
        }
    }

    private void addLabel() {
        //查询当前所选择牧场
        Pasture pasture = tablesDao.queryPastureById(App.select_pasture_id);
        String serialNumber = etSerialNumber.getText().toString();
//        if (serialNumber.equals("")) {
//            Toast.makeText(LabelAddActivity.this, "扫描蓝牙标签", Toast.LENGTH_SHORT).show();
//            return;
//        }
        String batteryLevel = tvBatteryLevel.getText().toString();
        String temperature = tvTemperature.getText().toString();
        String exerciseSteps = tvExerciseSteps.getText().toString();
        String name = etName.getText().toString();
        if (name.equals("")) {
            ToastUtils.showShort("更新成功");
            return;
        }
        String weight = etWeight.getText().toString();
        if (weight.equals("")) {
            ToastUtils.showShort("未填写体重");
            return;
        }
        //添加label时，没有event事件填null，没有group群填null，
        Label label = new Label(serialNumber, name, sex, weight, breedingStatus, String.valueOf(App.select_label_type),
                "SC" + MyUtil.date2String(new Date()), QRCodeID, batteryLevel, temperature,
                exerciseSteps, pasture);
        int insert = tablesDao.insertLabel(label);
        if (insert == 1) {
            ToastUtils.showShort("新增成功");
            cleanUI();
        } else {
            ToastUtils.showShort("新增失败");
        }
    }

    private void updateLabel() {
        String serialNumber = etSerialNumber.getText().toString();
        String batteryLevel = tvBatteryLevel.getText().toString();
        String temperature = tvTemperature.getText().toString();
        String exerciseSteps = tvExerciseSteps.getText().toString();
        String name = etName.getText().toString();
        if (name.equals("")) {
            ToastUtils.showShort("未填写名称");
            return;
        }
        String weight = etWeight.getText().toString();
        if (weight.equals("")) {
            ToastUtils.showShort("未填写体重");
            return;
        }
        selectLabel.setSerialNumber(serialNumber);
        selectLabel.setBatteryLevel(batteryLevel);
        selectLabel.setTemperature(temperature);
        selectLabel.setExerciseSteps(exerciseSteps);
        selectLabel.setName(name);
        selectLabel.setWeight(weight);
        selectLabel.setBreedingStatus(breedingStatus);
        selectLabel.setSex(sex);
        int insert = tablesDao.updateLabel(selectLabel);
        if (insert == 1) {
            ToastUtils.showShort("更新成功");
            LabelAddActivity.this.finish();
        } else {
            ToastUtils.showShort("新增失败");
        }
    }

    private void cleanUI() {
        etSerialNumber.setText("");
        tvBatteryLevel.setText("");
        tvTemperature.setText("");
        tvExerciseSteps.setText("");
        etName.setText("");
        etWeight.setText("");
    }

    private void deleteLabel() {
        //判断牲畜是否与事件关联
        List<Event> events = tablesDao.queryEventForLabel(selectLabel);
        if (!ObjectUtils.isEmpty(events)) {
            String info = "该牲畜关联着事件，不能删除";
            ToastUtils.showShort(info);
            MyUtil.normalDialogOne(LabelAddActivity.this, "操作提示", info);
            return;
        }
        //判断牲畜是否与配种关联
        List<Breed> breeds = tablesDao.queryBreedForLabel(selectLabel);
        if (!ObjectUtils.isEmpty(breeds)) {
            String info = "该牲畜关联着配种，不能删除";
            ToastUtils.showShort(info);
            MyUtil.normalDialogOne(LabelAddActivity.this, "操作提示", info);
            return;
        }
        //判断牲畜是否与防治关联
        List<Vaccine> vaccines = tablesDao.queryVaccineForLabel(selectLabel);
        if (!ObjectUtils.isEmpty(vaccines)) {
            String info = "该牲畜关联着防治，不能删除";
            ToastUtils.showShort(info);
            MyUtil.normalDialogOne(LabelAddActivity.this, "操作提示", info);
            return;
        }
        int res = tablesDao.deleteLabel(selectLabel);
        if (res != 1) {
            ToastUtils.showShort("删除失败, label");
            return;
        }
        ToastUtils.showShort("删除成功");
        LabelAddActivity.this.finish();
    }
}
